import threading
import time
from collections import defaultdict


class MessageQueue:

    def __init__(self):
        self._dict = defaultdict(list)
        self._lock = threading.Lock()

    def __getitem__(self, key):
        with self._lock:
            return self._dict[key]

    def __setitem__(self, key, value):
        with self._lock:
            self._dict[key] = value

    def __delitem__(self, key):
        with self._lock:
            del self._dict[key]

    def get(self, key, default=None):
        with self._lock:
            return self._dict.get(key, default)

    def keys(self):
        with self._lock:
            return list(self._dict.keys())

    def values(self):
        with self._lock:
            return list(self._dict.values())

    def items(self):
        with self._lock:
            return list(self._dict.items())

    def write_message(self, message):
        key = f'{message.nick_name}@{message.group_name}'
        if key in self.keys():
            message_list = self.get(key, [])
            message_list.append(message)
        else:
            self[key] = [message]

    def read_message(self):
        for key, message_list in self.items():
            if len(message_list) > 0:
                if time.time() - message_list[0].receive_time >= 180:
                    return message_list
        return None


